<?php

namespace App\Utils;

/**
 * 数据分页处理工具类
 * @package App\Utils
 */
trait FyUtil
{
    public $fy_pgSize;  //页大小  take()
    public $fy_pgCount; //页总数
    public $fy_pgCur;   //当前页
    public $fy_pgUrl;   //页地址，绝对地址 http://xxx/
    public $fy_pgOffset; //计算出的数据偏移 skip()

    public $fy_search;  //支持携带分页搜索
    public $fy_count;  //数据总数


    /**
     * 分页构造器
     * @param $url     路由
     * @param $size    页大小
     * @param $search []   支持分页搜索
     * @return $this    支持链式操作
     */
    public function fyInit($url, $size, $search = "")
    {
        $this->fy_pgSize = $size;
        $this->fy_pgUrl = $url;
        $this->fy_search = $search;
        return $this;
    }

    /**
     * 计算分页的数据
     * @param $count    数据总数
     * @param $index    当前页面索引
     */
    public function fyCalc($count, $index)
    {
        //计算页总数
        $this->fy_count = $count;
        $this->fy_pgCount = ceil($count / $this->fy_pgSize);
        $this->fy_pgCount = $this->fy_pgCount <= 0 ? 1 : $this->fy_pgCount;

        //检查页码
        $index = $index <= 0 ? 1 : $index;
        $index = $index > $this->fy_pgCount ? $this->fy_pgCount : $index;

        //计算跳过数数据的偏移
        $this->fy_pgOffset = ($index - 1) * $this->fy_pgSize;
        $this->fy_pgCur = $index;
    }

    /**
     * 关联分页数据到模板视图
     */
    public function fyViewInit(&$data)
    {
        $data['fy_pgSize'] = $this->fy_pgSize;
        $data['fy_pgCount'] = $this->fy_pgCount;
        $data['fy_pgCur'] = $this->fy_pgCur;
        $data['fy_pgUrl'] = $this->fy_pgUrl;
        $data['fy_pgOffset'] = $this->fy_pgOffset;
        $data['fy_search'] = $this->fy_search;
        $data['fy_count'] = $this->fy_count;
        return $this;
    }
}